from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import redirect, reverse,render
import json
from common.my_jwt import MyJWT
from common.utils import Response,visitInfo
from django.conf import settings
from index.models import WebConfigModel
import re
import logging

LOGApi = logging.getLogger('api')


class MyMiddleware(MiddlewareMixin):

    visit_views = {}

    def process_request(self, request):
        try:
            no_auth_url = [
                '/login/','/user/login/','/varify/code/','/user/register/','/weixin/receive/text/',
                '/weixin/taobao/url/','/','/error/forbid/','/user/qqLogin/','/user/qqLogin_two/','/nav/index/','/nav/common/','/nav/tools/',
                '/nav/develop/'
            ]
            ip = request.META.get('REMOTE_ADDR')
            path = request.path
            # 路由功能开关
            new_path = re.sub('.*/(\d+)/','id',path)
            web_config = WebConfigModel.objects.filter(url=new_path, status=1).first()
            if web_config:
                return render(request,'error/forbid.html',{"forbid_tip":web_config.response_content})
                # return redirect(url,forbid_tip=web_config.response_content)
            if '/admin/' in path:
                pass
            elif path not in no_auth_url:
                token = request.COOKIES['token']
                jwt_key = settings.JWT_KEY
                myjwt = MyJWT(key=jwt_key)
                result,data = myjwt.decode(token)
                if not result:
                    url = reverse('user_login')
                    resp = HttpResponseRedirect(url)
                    resp.delete_cookie('token')
                    resp.delete_cookie('uid')
                    resp.delete_cookie('figureurl')
                    resp.delete_cookie('qq')
                    return resp
                else:
                    request.user_id = data.get('uid')
                    request.username = data.get('username')
        except Exception as e:
            url = reverse('user_login')
            resp = HttpResponseRedirect(url)
            resp.delete_cookie('token')
            resp.delete_cookie('uid')
            resp.delete_cookie('figureurl')
            resp.delete_cookie('qq')
            return resp

    def process_exception(self,request, exception):
        LOGApi.error(str(exception))
        url = reverse('forbid')
        return redirect(url)



class VisitInfoMiddleware(MiddlewareMixin):
    """
    后台权限认证中间件
    只对后台路由生效
    TODO:根据路由判断是否有权限访问
    """
    VISIT_URL_DICT = {
        '/':"首页",
        '/weixin/receive/text/':"微信公众号",
        '/admin/':"后台"
    }
    def process_request(self, request):
        url = request.path
        if url in VisitInfoMiddleware.VISIT_URL_DICT:
            visitInfo(request, LOGApi, url_name=VisitInfoMiddleware.VISIT_URL_DICT.get(url))

    def process_view(self, request, callback, callback_args, callback_kwargs):
        pass

